package com.financial.service.yspay.service.impl;

import com.alibaba.fastjson.JSON;
import com.financial.service.yspay.connector.SysconfigFeign;
import com.financial.service.yspay.constants.YsServiceEnumConstants;
import com.financial.service.yspay.dto.FinancialYsPayDTO;
import com.financial.service.yspay.service.FinancialYsPayBuildRequestParaService;
import com.financial.service.yspay.service.FinancialYsPayVerifyJsonSignService;
import com.financial.service.yspay.service.FinancialYsPaymentService;
import com.financial.service.yspay.utils.DateUtils;
import com.financial.service.yspay.utils.HttpUtils;
import com.financial.service.yspay.utils.JsonUtils;
import com.financial.service.yspay.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author WANGNING
 * @Email wyn20140226@aliyun.com
 * @Description //银盛代付服务调用处理
 * @Date 2019/11/20 10:46
 */
@Service
public class FinancialYsPaymentServiceImpl implements FinancialYsPaymentService {
    private static final Logger logger = LoggerFactory.getLogger(FinancialYsPaymentServiceImpl.class);

    @Value("${ysPaymentNotifyUrl}")
    private String ysPaymentNotifyUrl;

    @Value("${ysPaymentMethod}")
    private String ysPaymentMethod;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private FinancialYsPayBuildRequestParaService financialYsPayBuildRequestParaService;

    @Autowired
    private FinancialYsPayVerifyJsonSignService financialYsPayVerifyJsonSignService;

    /**
     * 银盛代付接口
     *
     * @param requestParam
     * @return
     */
    @Override
    public ApiResult ysPayment(String requestParam) {
        logger.info("FinancialYsPaymentServiceImpl.ysPayment()---银盛代付服务请求参数json为:" + requestParam);
        String ysPaymentJson = sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsPaymentDTO = JsonUtils.parseObject(ysPaymentJson);        /*封装公共参数以及业务参数*/
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("method", ysPaymentMethod);
        paramsMap.put("partner_id", financialYsPaymentDTO.getPARTNER_ID_DF());
        paramsMap.put("timestamp", DateUtils.getNowTimeStr());
        paramsMap.put("charset", financialYsPaymentDTO.getDEFAULT_CHARSET());
        paramsMap.put("sign_type", financialYsPaymentDTO.getSIGN_ALGORITHM());
        paramsMap.put("version", financialYsPaymentDTO.getVERSION());
        paramsMap.put("notify_url", ysPaymentNotifyUrl);
        paramsMap.put("biz_content", requestParam);
        Map<String, Object> resultMap;
        /*返回内容初始化*/
        String content;
        try {
            /*签名*/
            Map<String, String> sPara = financialYsPayBuildRequestParaService.buildRequestParaDF(paramsMap, financialYsPaymentDTO);
            /*发起请求*/
            logger.info("FinancialYsPaymentServiceImpl.ysPayment()---签名完成的参数：" + sPara);
            String returnString = HttpUtils.httpsSend(financialYsPaymentDTO.getYSEPAY_GATEWAY_URL_DF(), sPara);
            logger.info("FinancialYsPaymentServiceImpl.ysPayment()---银盛非一清待打款接口返回信息:" + returnString);
            resultMap = (Map) JSON.parse(returnString);
            Map<String, String> obj = (Map<String, String>) resultMap.get("ysepay_df_single_quick_accept_response");
            boolean verifyResult = false;
            if (obj == null) {
                return ApiResult.failure(JsonUtils.objectToJson("银盛代付返回结果为空"));
            }
            int begin = returnString.indexOf("ysepay_df_single_quick_accept_response");
            content = returnString.substring(begin);
            content = content.replace("ysepay_df_single_quick_accept_response", "");
            content = content.substring(2, content.length() - 1);
            verifyResult = financialYsPayVerifyJsonSignService.verifyJsonSign(resultMap.get("sign").toString(), content, "utf-8", financialYsPaymentDTO);
            logger.info("FinancialYsPaymentServiceImpl.ysPayment()---代付请求回执信息,验签是否成功content:" + content + "验签结果verifyResult--" + verifyResult);
            if (null == content || content.equals("")) {
                logger.info("FinancialYsPaymentServiceImpl.ysPayment()---验签没有成功:银盛返回结果为空");
                return ApiResult.failure(JsonUtils.objectToJson("银盛返回结果为空"));
            }
            /*解析contrent*/
            Map<String, Object> contentMap = JsonUtils.jsonToMap(content);
            boolean tradeStatus = contentMap.containsKey("trade_status");
            logger.info("FinancialYsPaymentServiceImpl.ysPayment()----->代付通知成功是否包含trade_status" + tradeStatus);
            if (tradeStatus) {
                Object tempParams = contentMap.get("trade_status");
                String returnTradeStatus = tempParams == null ? null : tempParams.toString();
                if (returnTradeStatus.equalsIgnoreCase(YsServiceEnumConstants.ENUM_PAYMENTSTATUS_SUC)) {
                    /*TRADE_ACCEPT_SUCCESS是预代付成功标识*/
                    return ApiResult.success(content);
                } else {
                    /*失败返回*/
                    return ApiResult.failure(content);
                }
            } else {
                /*失败返回*/
                return ApiResult.failure(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FinancialYsPaymentServiceImpl.ysPayment()---银盛非一清待打款接口" + e.getMessage());
        }
        return ApiResult.failure(requestParam);
    }
}
